﻿using System.IO;
using HK.Core.Common.Data;
using HK.Core.IO.Protocol.Output;
using HK.Core.Utils;

namespace HK.Core.IO.Output
{
    /// <summary>
    /// Json文件I/O
    /// </summary>
    /// <typeparam name="TJson">Json数据类型</typeparam>
    public sealed class JsonFileIO<TJson> : FileIO<TJson>, IJsonFileIO<TJson>
        where TJson : JsonData
    {

#region Create

        /// <summary>
        /// 创建Json文件I/O对象
        /// </summary>
        /// <param name="iJson">Json数据对象</param>
        /// <param name="iPath">路径</param>
        /// <typeparam name="TJson">Json数据类型</typeparam>
        /// <returns>Json文件I/O对象</returns>
        public static JsonFileIO<TJson> Create<TJson>(TJson iJson, string iPath)
            where TJson : JsonData
        {
            return new JsonFileIO<TJson>
            {
                Mode = FileIoMode.Json,
                Data = iJson, Path = iPath
            };
        }

#endregion
        
        /// <summary>
        /// 保护构造函数
        /// </summary>
        private JsonFileIO() {}

#region Import

        /// <summary>
        /// 执行导入
        /// </summary>
        /// <returns>true:OK; false:NG;</returns>
        protected override bool DoImport()
        {
            var importData = UtilsSAssets.ImportFromJsonByPathSync<TJson>(Path);
            if (null == importData || !importData.Valid)
            {
                Warning("DoImport():Failed!(Path:{0})", Path);
                return false;
            }
            Data = importData;
            return default(TJson) != Data && Data.Valid;
        }

#endregion

#region Export

        /// <summary>
        /// 执行导出
        /// </summary>
        /// <returns>true:OK; false:NG;</returns>
        protected override bool DoExport()
        {
            var exportPath = UtilsSAssets.ExportToJsonSync(Data, Path);
            if (string.IsNullOrEmpty(exportPath))
            {
                Error("DoExport():The path of export is null!(Type::{0})", Data.GetType().Name);
                return false;
            }

            if (!exportPath.Equals(Path))
            {
                Error("DoExport():Failed!(Path:{0})", Path);
                return false;
            }
            return File.Exists(Path);
        }

#endregion

    }
}